import React, { useEffect, useState, useCallback } from 'react';
import QRCode from 'qrcode';
import {
  Modal,
  Typography,
  Message,
  Statistic,
  Result,
  Button,
  Spin,
} from '@arco-design/web-react';
import {
  RechargeType,
  PayWayType,
} from '@/pages/telepathy/educationTelepathy/enum';
import styles from './style/index.module.less';
import {
  createEnterpriseTelepathyOrder,
  createEnterpriseWalletOrder,
} from '@/api/wallet.js';
import PubSub from 'pubsub-js';

const { Text } = Typography;
const Countdown = Statistic.Countdown;

type ResultStatusType =
  | null
  | 'success'
  | 'error'
  | 'info'
  | 'warning'
  | '404'
  | '403'
  | '500';

enum Status {
  UnPay,
  Paying,
  PayEnd,
}

interface Props {
  visible: boolean;
  title: string;
  payAmount: number; // 支付金额
  rechargeType: RechargeType; //充值类型
  payWay: PayWayType; // 支付方式
  handleChangeVisible: (visible: boolean) => void;
  onConfirm: (vlaue: any) => void;
}

function PayModal(props: Props) {
  const {
    visible,
    payAmount,
    title,
    rechargeType,
    payWay,
    handleChangeVisible,
  } = props;

  const [loading, setLoading] = useState(false);
  const [status, setStatus] = useState<Status>(Status.UnPay);
  const [payCodeUrl, setPayCodeUrl] = useState('');
  const [orderAmount, setOrderAmount] = useState(0);
  const [remainTime, setRemainTimet] = useState(0);
  const [resultStatus, setResultStatus] = useState<ResultStatusType>(null);
  const [resultText, setResultText] = useState('');
  const [now, setNow] = useState(Date.now());
  const [payOrderId, setPayOrderId] = useState('11111');

  const changeVisible = () => {
    handleChangeVisible(false);
  };

  const getQRcode = (QRlink: string) => {
    QRCode.toDataURL(
      QRlink,
      { errorCorrectionLevel: 'L', margin: 2, width: 128 },
      (err, url) => {
        if (err) throw err;
        setPayCodeUrl(url);
      }
    );
  };

  // 创建订单
  const createOrder = async () => {
    setLoading(true);
    let res;
    // 充值钱包
    if (rechargeType === RechargeType.RechargeWallet) {
      const reqData = {
        CreateEnterpriseWalletOrderParam: {
          Amount: payAmount,
          PayProvider: payWay,
        },
      };
      res = await createEnterpriseWalletOrder(reqData);
    } else if (rechargeType === RechargeType.RechargeInpiration) {
      const reqData = {
        CreateEnterpriseTelepathyOrderParam: {
          BuyQuantity: payAmount,
          PayProvider: payWay,
        },
      };
      res = await createEnterpriseTelepathyOrder(reqData);
    }

    setLoading(false);

    if (res.StatusCode === 200) {
      if (!res.Result.PayCodeUrl) {
        Message.error('订单生成失败，请重试');
        setTimeout(() => {
          changeVisible();
        }, 300);
        return;
      }
      setPayOrderId(res.Result.OrderId);

      getQRcode(res.Result.PayCodeUrl);
      setOrderAmount(res.Result.OrderAmount);
      setRemainTimet(res.Result.RemainTime);
    } else {
      Message.error(res.Message + '，请重试');
      setTimeout(() => {
        changeVisible();
      }, 300);
    }
  };

  const remainTimeFinish = () => {
    setResultStatus('warning');
    setResultText('未在规定时间内支付，订单已自动关闭');
    setStatus(Status.PayEnd);
  };

  const handlePaySuccessSub = useCallback(
    (msg: string, data: any) => {
      if (data.OrderId === payOrderId && data.Content == '支付成功') {
        setResultStatus('success');
        setResultText('支付成功');
        setStatus(Status.PayEnd);
      }
    },
    [payOrderId]
  );

  useEffect(() => {
    const paySuccessSub = PubSub.subscribe(
      'PaySuccessMessage',
      handlePaySuccessSub
    );
    return () => {
      PubSub.unsubscribe(paySuccessSub);
    };
  }, [handlePaySuccessSub]);

  useEffect(() => {
    if (visible) {
      setOrderAmount(0);
      setRemainTimet(0);
      setNow(Date.now());
      setPayCodeUrl('');
      setResultStatus(null);
      setResultText('');
      setStatus(Status.UnPay);
      createOrder();
    }
  }, [visible]);

  return (
    <Modal
      title={title}
      visible={visible}
      autoFocus={false}
      focusLock={false}
      footer={null}
      onCancel={changeVisible}
      style={{ width: '600px' }}
    >
      {status === Status.UnPay ? (
        <div className={styles.payBox}>
          {loading && <Spin loading size={50} style={{ margin: '50px 0' }} />}
          {!!payCodeUrl && (
            <img className={styles.payCodeUrl} src={payCodeUrl} alt="" />
          )}
          <div style={{ marginBottom: 10 }}>
            ￥
            <Text style={{ color: '#ffc14e', fontSize: '30px' }}>
              {orderAmount}
            </Text>
          </div>
          {!!remainTime && (
            <Countdown
              value={now + remainTime}
              now={now}
              onFinish={remainTimeFinish}
            />
          )}
          <Text style={{ marginBottom: 10 }}>请在倒计时结束前完成支付</Text>
        </div>
      ) : (
        <div>
          <Result
            status={resultStatus}
            title={resultText}
            //icon={
            //  status === Status.Paying ? (
            //    <IconLoading style={{ color: 'rgb(var(--arcoblue-6))' }} />
            //  ) : null
            //}
            extra={
              <Button type="primary" onClick={changeVisible}>
                返回
              </Button>
            }
          ></Result>
        </div>
      )}
    </Modal>
  );
}

export default PayModal;
